package com.ruoyi.web.controller.system;


import cn.hutool.json.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.FileUploadUtils;
import com.ruoyi.common.utils.ServerConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 通用请求处理
 *
 * @author
 */

@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/common")
public class CommonController {

    private final ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public R<JSONObject> uploadFile(MultipartFile file, String pathPrefix) throws Exception {
        try {
            // 上传文件路径 添加上传图片默认文件夹前缀
            if (!StringUtils.isNotBlank(pathPrefix)) {
                pathPrefix = "picture";
            }

            String filePath = RuoYiConfig.getProfile() + File.separator + pathPrefix;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = fileName;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", file.getOriginalFilename());
            jsonObject.put("url", url.replaceAll("\\\\", "/"));
            return R.ok(jsonObject);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
